package com.cloudpivot.receivales.ding.robot.controller;

import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.contract.domain.NormalReturn;
import com.cloudpivot.receivales.ding.basic.service.impl.HttpAPIServiceForDing;
import com.cloudpivot.receivales.ding.robot.domain.RobotResDTO;
import com.cloudpivot.receivales.ding.robot.service.DocSpaceServiceImpl;
import com.cloudpivot.receivales.ding.robot.service.RobotServiceImpl;
import com.cloudpivot.receivales.ding.robot.util.SpringContextUtil;
import com.cloudpivot.receivales.ding.util.DingUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Method;
import java.util.*;

/**
 * 钉钉机器人 接口服务
 */
@Controller
@Slf4j
@RequestMapping("/dingrobot/")
public class RobotController {

    @Autowired
    private HttpAPIServiceForDing httpAPIServiceForDing;

    @Autowired
    private DocSpaceServiceImpl docSpaceService;

    @Autowired
    private RobotServiceImpl robotService;

    private Map<String,String> defalutMap;

    public RobotController(){
        log.info("导航map创建完成");
        Map<String, String> map = new HashMap<>();
        map.put("产品价格\\+", "productCardPush");
        map.put("报修\\+", "itServicePush");
        map.put("知识库\\+", "workspaceCardPush");
        map.put("修改部门\\+", "changeMaycurUserDept");
        this.defalutMap = map;
    }


    @GetMapping("/getFilename")
    @ResponseBody
    public JSONObject getFilename(String nameKey){
        Map<String, String> ret = docSpaceService.searchFileName(nameKey);
        return JSONObject.parseObject(JSONObject.toJSONString(ret));
    }


    /**
     * 机器人 回答 入口
     *
     * @param entity
     */
    @PostMapping("/callBackMsg")
    @ResponseBody
    public void getRobotMsg(@RequestBody JSONObject entity) {
        log.info("机器人回调报文:{}", JSONObject.toJSONString(entity));

        RobotResDTO dto = JSONObject.toJavaObject(entity, RobotResDTO.class);
        JSONObject textJsonObject = dto.getText();

        //获取具体内容
        String textContent = DingUtil.getJsonInsideValue(textJsonObject, "content");
        //获取钉钉userid
        String userId = dto.getSenderStaffId();

        //无上下文钉钉机器人返回异常
        if (StringUtils.isBlank(textContent)) {
            robotService.answerErrorMsg(Arrays.asList(userId),dto);
        }

        //获取机器人提问结果+方法
        Map<String, String> retMap = splitStr(textContent, defalutMap);
        if (Objects.isNull(retMap)) {
            //不在既定格式中的 返回标准模版
            robotService.productDefaultPush(Arrays.asList(userId),"",dto);
        }else{
            try {
                Class clazz = robotService.getClass();
                Method method = clazz.getMethod(retMap.get("method"), List.class, String.class,RobotResDTO.class);
                method.invoke(SpringContextUtil.getBean("robotServiceImpl"), Arrays.asList(userId), retMap.get("textContent"),dto);
            } catch (Exception e) {
                e.printStackTrace();
                robotService.productDefaultPush(Arrays.asList(userId),"",dto);
            }

        }
    }

    private Map<String, String> splitStr(String s, Map<String, String> map) {
        //key==方法 value==过滤结果
        try {
            Map<String, String> retMap = new HashMap<>();
            String args[] = null;
            //遍历
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String _key = entry.getKey();
                String _value = entry.getValue();
                args = s.split(_key);
                String _s = args[0];
                if (StringUtils.isBlank(_s)) {
                    //匹配成功 _s[0]==空
                    retMap.put("method", _value);
                    retMap.put("textContent", args[1]);
                    return retMap;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }


    //拦截报错
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public NormalReturn exceptionHandler(MethodArgumentNotValidException e) {
        NormalReturn resultJson = new NormalReturn(-1, "error");
        resultJson.setMsg(e.getBindingResult().getFieldError().getDefaultMessage());
        return resultJson;
    }
}
